var request = require('request')
var url = "http://www.xdaili.cn/ipagent/privateProxy/applyStaticProxy?count=1&spiderId=7851649904084460968857d54060a6b2&returnType=2"
var proxyList = []

var xdl = {
    getProxy: function () {
        request.get(url, function (err, res, body) {
            if (err) {
                setTimeout(function () {
                    this.getProxy()
                }.bind(this), 10 * 1000)
            }
            var r = JSON.parse(body)
            if (r.ERRORCODE == 0) {
                proxyList = proxyList.concat(r.RESULT)
            } else {
                setTimeout(function () {
                    this.getProxy()
                }.bind(this), 10 * 1000)
            }

        }.bind(this))
    },
    proxy: function () {
        console.log('切换代理')
        if (proxyList.length > 0) {
            var p = proxyList.shift()
            console.log("http://" + p.ip + ":" + p.port)
            return "http://" + p.ip + ":" + p.port
        } else {
            this.getProxy()
            return ""
        }
    }
}

module.exports = xdl